package com.hunk.springMvcExercise.web.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.HTML;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.hunk.utils.io.Print;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ContentType;

@Controller
@RequestMapping("/test")
public class TestConroller {
	@RequestMapping(value="/handle41")
	public String handle41(@RequestBody String requestBody) {
		Print.println(requestBody);
		return "test/handle41_success";
	}
	
	@RequestMapping(value="/handle42/{imageId}")
	public @ResponseBody byte[] handle42(@PathVariable("imageId") String imageId, HttpServletRequest request, HttpServletResponse response) throws IOException {
		Print.println("load image of " + imageId);	
		Resource res = new ClassPathResource(imageId + ".jpg");
		byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream());
		return fileData;
	}	
	
	@RequestMapping(value="/handle43")
	public String handle43(HttpEntity<String> httpEntity) {
		Print.println("http header: " +httpEntity.getHeaders());
		Print.println("http header: contentType = " + httpEntity.getHeaders().getContentType());
		Print.println("http header: content = " + httpEntity.getBody());
		return "test/handle43_success";
	}
	@SuppressWarnings("unused")
	private static class Test{
		public static void main(String[] args) throws IOException {
			testHeadle42();
		}
		
		public static void testHeadle43() {
			RestTemplate rt = new RestTemplate();
			MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
			form.add("userName","tom");
			form.add("password","12345");
			form.add("age","45");
			rt.postForLocation("http://localhost:8898/SpringMVC_Exercise/test/handle41.do",form);
		}
		
		public static void testHeadle42() throws IOException {
			RestTemplate rt = new RestTemplate();
			byte[] response = rt.postForObject(
					"http://localhost:8898/SpringMVC_Exercise/test/handle42/{03}.do", 
					null, byte[].class, "03");
			Resource outFile = new FileSystemResource("d:/image_copy.jpg");
			FileCopyUtils.copy(response, outFile.getFile());
		}
	}
}
